<!--
  采购订单管理
 -->

<template>
  <BaseMainSlot :show-tab="true" :show-btn-box="false">
    <template v-slot:btn-box>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-cancel="false"
        :has-save="false"
        :has-edit="false"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:tab-select>
      <SelectButton
        :buttonselectlist="buttonselectlist"
        @nowselectbuttonindex="batchstaumet"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <span class="label">订单编号:</span>
          <div class="input">
            <el-select v-model="searchInfo.orderNumber" filterable clearable>
              <el-option
                v-for="item in sellOrderLIst"
                :key="item.index"
                :label="item.orderNumber"
                :value="item.orderNumber"
              />
            </el-select>
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">销售人:</span>
          <div class="input">
            <el-input v-model="searchInfo.purchaserName" />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">销售客户:</span>
          <div class="input">
            <el-select v-model="searchInfo.customerNo" filterable clearable>
              <el-option
                v-for="item in customerList"
                :key="item.index"
                :label="item.customerName"
                :value="item.customerNo"
              />
            </el-select>
            <!-- <el-input v-model="searchInfo.deliveryName"></el-input> -->
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">销售日期:</span>
          <div class="input">
            <StartTimeEndTimeSelectionBox
              @startVal="startVal"
              @endVal="endVal"
            />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="salesOrderNo" label="订单编号" min-width="100" />
        <el-table-column prop="salesPersonName" label="销售人" />
        <el-table-column prop="salesDate" label="销售日期" min-width="100" />
        <el-table-column prop="customerName" label="销售客户" />
        <el-table-column width="200" label="销售产品">
          <template v-if="scope.row.salesOrderNo" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              @click="handledbCheck(scope.row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="curTabIndex == 0" width="140" label="操作">
          <template v-if="scope.row.salesOrderNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(60, 'verify')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-check"></i> 通过
            </el-button>
            <el-button
              v-if="judgePermission(60, 'verify')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
            >
              <i class="el-icon-close"></i> 不通过
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="curTabIndex != 0"
          prop="auditDate"
          label="审核日期"
          min-width="100"
        />
        <el-table-column v-if="curTabIndex == 2" width="120" label="操作">
          <template v-if="scope.row.salesOrderNo" slot-scope="scope">
            <el-popover
              placement="top-start"
              title="拒绝原因"
              width="200"
              trigger="hover"
              :content="scope.row.remarks"
            >
              <el-button
                slot="reference"
                class="text-btn-cursor"
                type="text"
                size="small"
              >查看原因</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <!-- 详细信息 -->
      <el-dialog
        title="详细信息"
        :visible.sync="purchaseVisible"
        width="60%"
        class="purchase"
      >
        <el-row>
          <h4 class="total-price">
            <span>销售物品明细:</span>
            <span>销售总金额:{{ totalAmount }}元</span>
          </h4>
          <el-table
            ref="rightTableData"
            :data="rightTableData"
            tooltip-effect="dark"
            highlight-current-row
            border
            stripe
            class="rightTableData"
          >
            <el-table-column label="产品编码" prop="goodsNo" align="center" />
            <el-table-column label="产品名称" prop="goodsName" min-width="95" />
            <el-table-column label="规格" prop="specification">
              <template
                slot-scope="scope"
              >{{ scope.row.specification }} {{ scope.row.perSpecUnitName }}/{{ scope.row.unitName }}</template>
            </el-table-column>
            <el-table-column label="型号" prop="model" />
            <el-table-column label="产品单价" prop="unitPrice" />
            <el-table-column label="销售数量" prop="salesQuantity" min-width="95" />
            <el-table-column label="单位" min-width="75" prop="unitName" />
            <el-table-column label="优惠金额" prop="discountPrice" min-width="95" />
            <el-table-column label="物品总价" prop="totalAmount" min-width="95" />
            <template slot="empty">
              <div>请添加数据</div>
            </template>
          </el-table>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button
            class="zh-button-two"
            type="primary"
            @click="purchaseVisible = false"
          >确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :title="'拒绝原因'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="不通过原因:" prop="reason" class="w100p">
            <el-input v-model="formData.reason" clearable />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SearchBox from "@/components/SearchBox";
import { mymixin } from "@/utils/mixin";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
// import baseQuery from "@/api/digital-operation/base"
import SelectButton from "@/components/selectbutton/index.vue";
import sellOrderManage from "@/api/digital-operation/sell-order-manage/sell-order-manage";
import customerManage from "@/api/digital-operation/sell-order-manage/customer-manage";
import { mapGetters } from "vuex";
export default {
  name: "SellOrderExamine",
  components: {
    BaseMainSlot,
    ActionBar,
    Pagination,
    StartTimeEndTimeSelectionBox,
    SearchBox,
    SelectButton
  },
  mixins: [mymixin],
  data() {
    return {
      searchInfo: {},
      // 名称
      name: "",
      nameList: [],
      price: "",
      number: "",
      // 采购物品
      goodsId: "",
      goodsList: [],
      unitName: "",
      rulesTime: "",
      // 人員名稱
      purchaser: "",
      // 供應商名稱
      supplierId: "",
      totalPrice: 0,
      // 采购订单名称
      orderNumber: "",
      agriculturalMaterialName: "",
      StaffData: [],
      // 采购部门列表
      supplierList: [],
      paramNamelist: [],
      selectlistRow: [],
      salseProductsName: [],
      // 农资类型
      agriMateArr: [],
      sellOrderLIst: [],
      rightTableData: [],
      // addformData 添加的表单
      addformData: {},
      // 控制表格 添加行 input 显示隐藏
      addHide: true,
      purchaseVisible: false,
      dialogFormVisible: false,
      totalAmount: 0,
      endTime: "",
      startTime: "",
      titleText: "",
      startDatePickers: this.beginDates(),
      endDatePickers: this.processDates(),
      rules: {
        procurementTime: [
          { required: true, message: "请选择采购时间", trigger: "change" }
        ],
        deliveryTime: [
          { required: true, message: "请选择交货时间", trigger: "change" }
        ],
        purchaser: [
          { required: true, message: "请选择采购申请人", trigger: "change" }
        ],
        suppilerId: [
          { required: true, message: "请选择采购部门", trigger: "change" }
        ]
      },
      buttonselectlist: [
        { name: "未审核" },
        { name: "通过审核" },
        { name: "未通过审核" }
      ],
      curTabIndex: 0,
      customerList: []
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    rightTableData: {
      deep: true,
      handler(val) {
        let arr = [];
        val.forEach(item => {
          if (item.salesQuantity && item.unitPrice) {
            item.totalAmount =
              parseFloat(item.salesQuantity) * parseFloat(item.unitPrice) -
              parseFloat(item.discountPrice);
            arr.push(item.totalAmount);
            item.totalPriceItem = item.totalAmount.toFixed(2);
          } else {
            item.totalPriceItem;
          }
        });
        sum(arr);
        function sum(arr) {
          var s = 0;
          for (var i = arr.length - 1; i >= 0; i--) {
            s += arr[i];
          }
          return s;
        }
        this.totalAmount = sum(arr).toFixed(2) || 0;
        // console.log(sum(arr))
      }
    },
    addformData: {
      deep: true,
      handler(val) {
        // console.log(val)
        if (val.number && val.price) {
          // 当input值改变时计算
          this.$set(
            val,
            "totalPriceItem",
            (parseFloat(val.number) * parseFloat(val.price)).toFixed(2)
          );
        }
      }
    }
  },
  created() {
    this.queryDatalist();
  },
  mounted() {
    // 表格分页数据
    this.getTableDataList();
  },
  methods: {
    batchstaumet(index) {
      this.curTabIndex = index;
      this.getTableDataList();
    },
    // 获取 表格数据
    getTableDataList() {
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        sort: "timestamp",
        entity: {
          auditStatus: this.curTabIndex,
          ...this.searchInfo
        }
      };
      if (param.entity.salesOrderNo === "") {
        param.entity.salesOrderNo = null;
      }
      sellOrderManage.queryPageByCondition(param).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          // console.log(data);
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    async queryDatalist() {
      // 查询客户名称
      let res = await customerManage.queryByCondition({});
      this.customerList = res.data;
    },
    // 搜索框时间
    startVal(e) {
      this.startTime = e;
    },
    endVal(e) {
      this.endTime = e;
    },
    beginDates() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.deliveryTime) {
            //  如果结束时间不为空，则小于结束时间
            return (
              new Date(self.formData.deliveryTime).getTime() < time.getTime()
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDates() {
      const self = this;
      // if (self.endTime) {
      return {
        disabledDate(time) {
          if (self.formData.procurementTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return (
              new Date(self.formData.procurementTime).getTime() > time.getTime()
            );
          } else {
            return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    selectable(row, index) {
      // console.log(row)
      // if (row.status === true) {
      //   this.$message.warning('1')
      // }
      return row.status === true; // 通过某个值来进行判断，规定那一行的选择框被禁用
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 时间
    dateFormat(row, colnum) {
      if (row.deliveryTime) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    async handleEdit(row) {
      if (row.salesOrderNo) {
        this.openDialog("edit");
        this.formData = JSON.parse(JSON.stringify(row));
      }
    },
    async handledbCheck(row) {
      if (row.salesOrderNo) {
        this.formData = JSON.parse(JSON.stringify(row));
        // this.employeeId = this.formData.name
        let {
          data: salesOrderGoodsList
        } = await sellOrderManage.queryListBySalesOrderNo(row.salesOrderNo);
        // 回显
        salesOrderGoodsList.forEach(item => {
          if (item.perSpecUnitId) {
            item["perSpec"] = item.perSpecUnitName;
          }
        });
        this.rightTableData = salesOrderGoodsList;
        this.purchaseVisible = true;
      }
    },
    handleSelectionChange(list) {
      this.purchaseOrderIdList = [];
      this.purchaseOrderIdList = list.map(item => item.purchaseOrderId);
      if (this.purchaseOrderIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    handleDelete(row) {
      this.$alert("确认通过该记录", "通过销售订单", {
        confirmButtonText: "确定",
        callback: action => {
          if (action === "confirm") {
            sellOrderManage
              .updateAuditStatus({
                salesOrderNo: row.salesOrderNo,
                auditStatus: 1
              })
              .then(res => {
                if (res.code !== 1) {
                  return;
                }
                this.getTableDataList();
              });
          }
        }
      });
    },
    handleClose(done) {
      this.resetActionBar();
      done();
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        sellOrderManage
          .updateAuditStatus({
            salesOrderNo: this.formData.salesOrderNo,
            auditStatus: 2,
            remarks: this.formData.reason
          })
          .then(res => {
            if (res.code !== 1) {
              return;
            }
            this.closeDialog();
            this.getTableDataList();
          });
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.search-item {
  display: flex;
  height: 36px;
  margin-left: 20px;
  white-space: nowrap;
  &:first-child {
    margin: 0;
  }
  span {
    display: inline-block;
  }
  &.rules-wrap span {
    padding: 0 15px;
    border: 1px solid $borderColor;
    cursor: pointer;
    line-height: 35px;
    transition: border-color 0.2s;
    box-sizing: border-box;
    &:hover {
      border-color: #6ecae3;
    }
  }
}
.purchase {
  ::v-deep .el-dialog {
    border: 1px solid #000;
    border-radius: 10px;
    .el-dialog__header {
      border-radius: 9px 9px 0 0;
      .el-dialog__title {
        color: #fff;
      }
    }
    .el-dialog__body {
      padding: 5px 20px;
      font-size: 12px !important;
      .el-input {
        input {
          font-size: 12px;
        }
      }
    }
    .el-table {
      max-height: 200px;
      overflow-y: auto;
      background-color: rgba(255, 255, 255, 1);
      .cell {
        color: #000;
      }
      th {
        background-color: rgba(230, 230, 230, 1);
      }
      th.is-leaf {
        border-color: rgba(77, 77, 77, 1);
      }
      td {
        border-color: rgba(77, 77, 77, 1);
      }
      tr:hover {
        background-color: rgba(77, 77, 77, 1);
      }
      .el-table__empty-text {
        color: #000;
      }
      .current-row {
        // background-color: rgb(177, 177, 177);
        background-color: #dbdbdb !important;
      }
      .el-table__row--striped {
        background-color: rgba(255, 255, 255, 1);
      }
      // color: #000;
    }
    .el-table--border {
      border-color: rgba(77, 77, 77, 1);
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .el-table--enable-row-hover .el-table__body tr:hover > td {
      background-color: rgb(177, 177, 177);
    }
    .el-table__body tr.current-row > td {
      background-color: #dbdbdb !important;
    }
    .el-form-item {
      margin-bottom: 10px;
    }
    .total-price {
      color: #000;
    }
    .el-table__body {
      // height: ;
      height: 0;
      // background-color: #003947;
    }
  }
}
.el-date-editor,
.el-select {
  width: 100%;
}

h4.total-price {
  display: flex;
  justify-content: space-between;
  margin: 0;
  color: #fff;
  margin-bottom: 5px;
}

.right-table {
  line-height: 0px;
}
.addInfo {
  width: 100%;
}
.rightTableData {
  // .
  ::v-deep .el-table--border {
    border: #5fb6cd;
  }
  ::v-deep .cell {
    margin: 0 !important;
    // padding: 0 !important;
    font-size: 10px;
  }
  ::v-deep .el-table th {
    margin: 0 !important;
    padding: 0 !important;
    font-size: 10px;
  }
  ::v-deep .el-table--medium th {
    margin: 0 !important;
    padding: 0 !important;
    font-size: 10px;
  }
}
.total {
  ::v-deep .el-input__inner {
    border-right: 1px solid #6ecae3 !important;
  }
}
::v-deep .el-dialog__wrapper {
  .el-dialog {
    // width: 70% !important;
    .el-select {
      width: 100% !important;
    }
    .el-dialog__body {
      .el-form {
        .el-row {
          .el-table {
            max-height: 267px !important;
            .el-table__header-wrapper {
              position: fixed;
              z-index: 99;
            }
            .el-table__body-wrapper {
              margin-top: 38px;
            }
          }
        }
      }
    }
  }
}
</style>
